package socketdemo3;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/*
 * 客户端
 * */
public class Client {
    /*客户端socket对象*/
    private Socket socket;

    public Client() {
        try {
            socket = new Socket("localhost", 8088);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 作为整个程序的开始
     */
    private void start() {
        try {
            //网络输出流
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true); //打开自动行刷新

            Runnable runnable = new MessageReception();
            Thread thread = new Thread(runnable);
            thread.setDaemon(true);
            thread.start();

            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("请输入信息:");
                String line = scanner.nextLine();
                //当line接收到的数据为exit时循环结束
                if ("exit".equals(line)) break;
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    private class MessageReception implements Runnable {
        @Override
        public void run() {
            try {
                //网络输入流
                InputStream is = socket.getInputStream();
                InputStreamReader irs = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(irs);

                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println("服务端:" + line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

